import redis
import pickle
from jili.tool.state import  isredis
if isredis:
    pool = redis.ConnectionPool(host='127.0.0.1')
    r = redis.Redis(connection_pool=pool)

def setredis(key, value):
    if isredis:
        r.set(key, pickle.dumps(value))

def setredis_map(name, key, data):
    if isredis:
        r.hset(name, key, pickle.dumps(data))

def setredis_mapall(name, data):
    if isredis:
        # print(name,data)
        for k, v in data.items():
            r.hset(name, k, pickle.dumps(v))

def getredis(key):
    if isredis:
        p = r.get(key)
        if p:
            return pickle.loads(p)
        else:
            return {}
    else:
        return {}

def getredis_map(name, key=""):
    if isredis:
        if key == "":
            p = r.hgetall(name)
            if p:
                ret = {}
                for k, v in p.items():
                    k1 = str(k, encoding="utf")
                    ret[k1] = pickle.loads(v)
                return ret
            else:
                return {}
        else:
            p = r.hget(name, key)
            if p:
                return pickle.loads(p)
            else:
                return {}
    else:
        return {}